package com.aspect;

import com.bean.anno.LogAnno;
import com.bean.base.LogInfo;
import com.mapper.repository.LogInfoRepository;
import com.utils.JWTUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.UUID;

@Aspect
@Component
@Slf4j
public class LogAspect {

//    @Autowired
//    private UserLogInfoService userLogInfoService;

    @Autowired
    private JWTUtil jwtUtil;

    @Autowired
    private LogInfoRepository logInfoRepository;

    @Pointcut("@annotation(com.bean.anno.LogAnno)")//表示只要是加了@LoginAnno这个注解的方法，都会被拦截
    public void pointcut() {

    }

    @Around("pointcut()")
    public Object aroundAdvice(ProceedingJoinPoint joinPoint) throws Throwable {
        Object[] args = joinPoint.getArgs();//获取得是切点中的参数信息
        log.info("调用了方法arroundAdvice切面方法");

        MethodSignature signature = (MethodSignature) joinPoint.getSignature();//

        Method method = signature.getMethod();

        /*HttpServletRequest request=null;
        for(Object obj:args){
            if (obj instanceof HttpServletRequest) {
                request= (HttpServletRequest) obj;
                log.info(request.getRemoteHost());//输出ip地址
            }
        }*/
        // 获取当前请求的 HttpServletRequest 对象

        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes != null) {
            LogInfo logInfo =new LogInfo();
            HttpServletRequest request = attributes.getRequest();
            String ipAddress = request.getRemoteAddr();  // 获取 IP 地址

            String token=request.getHeader("token");
            if(token!=null&&!token.equals("")){
                String userid=jwtUtil.getClaimKeyUsername(token);
                logInfo.setUserid(userid);
            }
            LogAnno logAnno=method.getAnnotation(LogAnno.class);
            logInfo.setId(UUID.randomUUID().toString());
            logInfo.setIp(ipAddress);
            logInfo.setLog(logAnno.details());
            logInfo.setCreatetime(LocalDateTime.now());
            logInfoRepository.save(logInfo);
        }


        Object result = null;
        try {
            result = joinPoint.proceed();//执行切点方法
        } catch (Throwable e) {
            log.error(e.toString());
            throw e;
        }
        return result;
    }
}
